package com.afishing.servlet;

import com.afishing.dao.CartDao;
import com.afishing.dao.impl.CartDapImpl;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "RemoveCartServlet", value = "/removeCart")
public class RemoveCartServlet extends HttpServlet {
    private final CartDao cartDao = new CartDapImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        // 从请求中获取商品ID
        String id = request.getReader().lines().reduce("", (accumulator, actual) -> accumulator + actual);
        System.out.println(id);
        //{"id":2}
        // 解析json字符串
        JSONObject jsonObject = JSONObject.parseObject(id);
        id = jsonObject.getString("id");

        // 删除数据库中的商品
        cartDao.removeShop(Integer.parseInt(id));

        // 返回响应给客户端
        response.getWriter().write("success");
    }
}